import React from 'react'
import * as _ from 'lodash'
import { Chart, Geom, Axis, Tooltip, Coord, Legend, Guide } from 'bizcharts'
import { Spin, Button } from "antd"
import { WeaAlertPage, WeaLocaleProvider, WeaDialog, WeaTable, WeaTools } from 'ecCom'

const getLabel = WeaLocaleProvider.getLabel

export default class ChartPanel extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
      panelWidth: 0,
      moreDialogVisible: false, // 更多显隐
      moreDialogTitle: '',
      moreDialogTableColumns: [],
      moreDialogTableDatas: [],
      moreDialogTablePageSize: 10,
      moreDialogTablePageCurrent: 1,
      moreDialogTableTotal: 0,
      moreDialogTableInterface: {},
      moreDialogTableBaseRequestParams: {},
      moreDialogTableLoading: false,
      ...props
    }
  }

  componentWillMount() {

  }

  componentWillReceiveProps(newProps) {
    this.setState({
      ...this.state,
      ...newProps
    })
  }

  getSloganHtml = (slogan) => {
    if (_.isString(slogan)) {
      return `${slogan}`
    } else if (_.isArray(slogan)) {
      let result = slogan[0]
      Object.keys(slogan[1] || {}).forEach(key => {
        let reg
        if (result.indexOf("$") > -1) {
          reg = "${" + key + "}"
        } else {
          reg = `&${key}&`
        }
        result = result.replace(reg, `<span style="font-size: 18px; padding: 0 5px; color: ${slogan[1][key].color || '#333'}">${slogan[1][key].label}</span>`)
      })
      return result
    }
  }

  getLegendItem = (width, height, value, text, dotColor, needBorder) => {
    return (
      <div className="chart-legend-item" style={{ width, height: height || "auto", marginBottom: "10px", borderLeft: needBorder ? "1px solid #E2E2E2" : "none" }}>
        <div className="value-wrapper">{value}</div>
        <div className="text-wrapper">
          <i className="dot-icon" style={{ background: dotColor }} />
          <span>{text}</span>
        </div>
      </div>
    )
  }

  // 根据接口code获取数据
  getDataByInterfaceCode = (code) => {
    const { subId, deptId, includeSub, interfacesInfo } = this.state
    const interfaceObj = interfacesInfo[code]
    if (interfaceObj && interfaceObj.addr) {
      return WeaTools.callApi(interfaceObj.addr, interfaceObj.method || "GET", {
        subId,
        deptId,
        includeSub: includeSub ? "1" : "0"
      })
    } else {
      return new Promise(rs => rs({}))
    }
  }

  getMoreDialogTableDatas = () => {
    const { moreDialogTablePageCurrent, moreDialogTablePageSize, moreDialogTableInterface, moreDialogTableDataSource, moreDialogTableBaseRequestParams, ismock } = this.state

    const handleRes = (res) => {
      this.setState({
        moreDialogTableLoading: false
      })
      const { data } = res
      if (data) {
        this.setState({
          moreDialogTableDataSource: data.data || [],
          moreDialogTableTotal: data.total || 0
        })
      }
    }

    if (moreDialogTableInterface && moreDialogTableInterface.addr) {
      this.setState({
        moreDialogTableLoading: true
      })
      WeaTools.callApi(moreDialogTableInterface.addr, moreDialogTableInterface.method || "GET", {
        ...moreDialogTableBaseRequestParams,
        pagenum: moreDialogTablePageCurrent,
        pagesize: moreDialogTablePageSize
      }).then(res => {
        handleRes(res)
      })
    } else {
      if (!ismock && moreDialogTableDataSource.length > 0) {                    // ismock is to delete
        handleRes({
          data: {
            total: moreDialogTableDataSource.length,
            data: moreDialogTableDataSource
          }
        })
      } 
      else {                     // to delete
        let dataSource = []
        let total = 60
        for (let i = (moreDialogTablePageCurrent - 1) * moreDialogTablePageSize; i < moreDialogTablePageSize * moreDialogTablePageCurrent; i++) {
          if (i < total) {
            dataSource.push({
              item: "测试" + i,
              count: i + 1
            })
          }
        }
        let res = {
          data: {
            total,
            data: dataSource
          }
        }
        handleRes(res)
      }
    }
  }

  onDialogTablePageCurrentChange = (current) => {
    this.setState({
      moreDialogTablePageCurrent: current
    }, () => {
      this.getMoreDialogTableDatas()
    })
  }

  onMoreTextClick = (params = {}) => {
    const { dialogTitle, tableColumns, dataSource, baseRequestParams } = params
    this.setState({
      moreDialogTitle: dialogTitle || '',
      moreDialogTableColumns: tableColumns || [],
      moreDialogTableDataSource: dataSource || [],
      moreDialogVisible: true,
      moreDialogTablePageCurrent: 1,
      moreDialogTablePageSize: 10,
      moreDialogTableTotal: 0,
      moreDialogTableInterface: params.interface,
      moreDialogTableBaseRequestParams: baseRequestParams || {}
    }, () => {
      this.getMoreDialogTableDatas()
    })
  }

  onMoreDialogCancleClick = () => {
    this.setState({
      moreDialogVisible: false,
      moreDialogTitle: '',
    });
  }

  render() {
    const { panelWidth, title, slogan, charts = [], style = {}, moreDialogVisible, moreDialogTitle, moreDialogTableColumns, moreDialogTableDataSource,
      moreDialogTableTotal, moreDialogTablePageCurrent, moreDialogTablePageSize, moreDialogTableLoading } = this.state

    return (
      <div className="wea-workrelate-portrait-chartpanel" style={style}>
        {
          (title || slogan) &&
          <div className="title-wrapper">
            {
              title && <span className="first-title">{title}</span>
            }
            {
              slogan && <span className="second-title" dangerouslySetInnerHTML={{ __html: this.getSloganHtml(slogan) }}></span>
            }
          </div>
        }
        <div className="charts-content" ref={ref => ref && this.state.panelWidth == 0 && this.setState({ panelWidth: ref.clientWidth - 20 })}>
          {
            charts.map((chart,index) => {
              const chartWidth = _.isNumber(chart.width) ? chart.width : (chart.width.replace("%", "") / 100) * panelWidth
              const chartHeight = chart.height ? chart.height : 338
              const canvansAndRightLegendWidth = chartWidth - 31   // 减去padding和border
              const rightLegendWidth = chart.rightLegend ? (_.isNumber(chart.rightLegend.width) ? chart.rightLegend.width : (chart.rightLegend.width.replace("%", "") / 100) * canvansAndRightLegendWidth) : 0
              const rightLegendRightPadding = 20   // rightLegend右侧padding
              const rightLegendItemWidth = chart.rightLegend ? (_.isNumber(chart.rightLegend.itemWidth) ? chart.rightLegend.itemWidth : (chart.rightLegend.itemWidth.replace("%", "") / 100) * (rightLegendWidth - rightLegendRightPadding)) : 0
              const rightLegengItemHeight = chart.rightLegend && chart.rightLegend.itemHeight
              const canvasWidth = canvansAndRightLegendWidth - rightLegendWidth
              const canvasHeight = chartHeight - 24 - 20 - (chart.nobottom ? 0 : (chart.bottomHeight || 50))

              const nodata = (
                <div style={{ width: canvasWidth, height: canvasHeight }}>
                  <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@v8luqb@${chart.type+index}`} icon={<i className="icon-coms-NoData" />} iconSize={35} >
                    <div style={{ textAlign: "center", marginTop: "4px" }}>
                      {getLabel(83553, "暂无数据")}
                    </div>
                  </WeaAlertPage>
                </div>
              )

              return (
                <div className="chart-item-wrapper" style={{ width: chart.width, height: chart.height, ...(chart.style || {}) }}>
                  {
                    (chart.hasmore || chart.extraCom) &&
                    <div className="extra-com-wrapper">
                      {
                        chart.hasmore ?
                          <span
                            className="more-wrapper"
                            onClick={() => {
                              this.onMoreTextClick({
                                dialogTitle: chart.title,
                                tableColumns: chart.moreProps.table.columns,
                                dataSource: chart.moreProps.table.dataSource,
                                interface: chart.moreProps.table.interface,
                                baseRequestParams: chart.moreProps.table.baseRequestParams,
                              });
                            }}
                          >
                            {'more>'}
                          </span>
                          :
                          chart.extraCom
                      }
                    </div>
                  }
                  <div className="chart-item-title">
                    {chart.title}
                  </div>
                  <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@5zsyfp@${chart.type+index}`} spinning={chart.loading || false}>
                    <div className="chart-item-main-content" style={{ borderLeft: chart.noborder ? "none" : "1px solid #E2E2E2" }}>
                      {
                        chart.type === "singleline" && (
                          !_.isEmpty(chart.data) ?
                            <div className="line-chart" style={{ width: canvasWidth, height: canvasHeight }} >
                              <div className="line-box">
                                {
                                  chart.data.map(d => {
                                    return <span className="seg-item" style={{ width: `${d.percent * 100}%`, background: d.color }}></span>
                                  })
                                }
                              </div>
                              <div className="line-textinfo">
                                {
                                  chart.data.map(d => {
                                    return (
                                      <div className="row-item">
                                        <span className="left-label">
                                          <i className="icon" style={{ background: d.color }} />
                                          {d.item}
                                        </span>
                                        <span className="right-label">{`${(d.percent * 100).toFixed(1)}%`}</span>
                                      </div>
                                    )
                                  })
                                }
                              </div>
                            </div>
                            :
                            nodata
                        )
                      }

                      {
                        chart.type === "pie" && (
                          (!_.isEmpty(chart.data) && chart.data.map(d => parseFloat(d.percent + "")).reduce((p1, p2) => p1 + p2) > 0) ?
                            <Chart ecId={`${this && this.props && this.props.ecId || ''}_Chart@z8tres@${chart.type+index}`} width={canvasWidth} height={canvasHeight} data={chart.data} padding="auto" forceFit>
                              <Coord ecId={`${this && this.props && this.props.ecId || ''}_Coord@f50fha@${chart.type+index}`} type="theta" radius={0.65} innerRadius={0.45} />
                              <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@lcvnml@${chart.type+index}`} showTitle={false} itemTpl='<li><span style="background-color:{color};" class="g2-tooltip-marker"></span>{name}: {value}</li>' />
                              <Geom ecId={`${this && this.props && this.props.ecId || ''}_Geom@gnoets@${chart.type+index}`} type="intervalStack" position="percent" color={["item", chart.data.map(d => d.color)]} size={chart.size || 25}
                                tooltip={[
                                  'item*percent',
                                  (item, percent) => {
                                    percent = `${(parseFloat(percent + "") * 100).toFixed(2)}%`
                                    return {
                                      name: item,
                                      value: percent
                                    }
                                  }
                                ]}
                                style={{
                                  lineWidth: 1,
                                  stroke: '#fff',
                                }}
                              />
                              {
                                chart.guideIcon &&
                                <Guide ecId={`${this && this.props && this.props.ecId || ''}_Guide@k2apfv`}>
                                  <Guide.Html ecId={`${this && this.props && this.props.ecId || ''}_undefined@yrz3tm`}
                                    position={['50%', '50%']}
                                    html={`<i class="${chart.guideIcon}" style="display:inline-block; color:#B7C3DB; transform: scale(2,2)" />`}
                                  />
                                </Guide>
                              }
                            </Chart>
                            :
                            nodata
                        )
                      }

                      {
                        chart.type === "bar" && (
                          !_.isEmpty(chart.data) ?
                            <Chart ecId={`${this && this.props && this.props.ecId || ''}_Chart@9mo15r@${chart.type+index}`} width={canvasWidth} height={canvasHeight} data={chart.data} scale={chart.scale} padding="auto" forceFit>
                              <Axis ecId={`${this && this.props && this.props.ecId || ''}_Axis@wxifkk@${chart.type+index}`} name="x" />
                              <Axis ecId={`${this && this.props && this.props.ecId || ''}_Axis@ysw590@${chart.type+index}`} name="y" />
                              <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@jzozau@${chart.type+index}`} showTitle={false} itemTpl='<li><span style="background-color:{color};" class="g2-tooltip-marker"></span>{xd}: {yd}</li>' />
                              <Geom ecId={`${this && this.props && this.props.ecId || ''}_Geom@oe2rwv@${chart.type+index}`} type="interval" position="xd*yd" color={["xd", chart.data.map(d => Array.isArray(d.color) ? "l(270) 0:#{c1} 1:#{c2}".replace("#{c1}", d.color[0]).replace("#{c2}", d.color[1] || d.color[0]) : d.color)]} size={chart.size || 30}
                                tooltip={[
                                  'xd*yd',
                                  (xd, yd) => {
                                    if (chart.scale && chart.scale.yd && chart.scale.yd.formatter) {
                                      yd = chart.scale.yd.formatter(yd)
                                    }
                                    return {
                                      xd,
                                      yd
                                    }
                                  }
                                ]}
                              />
                            </Chart>
                            :
                            nodata
                        )
                      }

                      {
                        chart.type === "strip" &&
                        (
                          !_.isEmpty(chart.data) ?
                            <Chart ecId={`${this && this.props && this.props.ecId || ''}_Chart@ilbffj@${chart.type+index}`} width={canvasWidth} height={canvasHeight} data={chart.data ? (chart.data.length > 5 ? chart.data.slice(0, 5) : chart.data) : []} padding="auto" forceFit>
                              <Coord ecId={`${this && this.props && this.props.ecId || ''}_Coord@lb4dkk@${chart.type+index}`} transpose />
                              <Axis ecId={`${this && this.props && this.props.ecId || ''}_Axis@avpzx4@${chart.type+index}`}
                                name="y"
                                label={{
                                  offset: 12
                                }}
                              />
                              <Axis ecId={`${this && this.props && this.props.ecId || ''}_Axis@4wcqhg@${chart.type+index}`} name="x" />
                              <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@ho54s8@${chart.type+index}`} itemTpl='<li><span style="background-color:{color};" class="g2-tooltip-marker"></span>{yd}: {xd}</li>' />
                              <Geom ecId={`${this && this.props && this.props.ecId || ''}_Geom@59v907@${chart.type+index}`} type="interval" position="yd*xd" color={["yd", chart.data.map(d => Array.isArray(d.color) ? "l(0) 0:#{c1} 1:#{c2}".replace("#{c1}", d.color[0]).replace("#{c2}", d.color[1] || d.color[0]) : d.color)]}
                                tooltip={[
                                  'xd*yd',
                                  (xd, yd) => {
                                    if (chart.scale && chart.scale.yd && chart.scale.yd.formatter) {
                                      yd = chart.scale.yd.formatter(yd)
                                    }
                                    return {
                                      xd,
                                      yd
                                    }
                                  }
                                ]} />
                            </Chart>
                            :
                            nodata
                        )
                      }

                      {
                        chart.type === "line" &&
                        (
                          !_.isEmpty(chart.data) ?
                            <Chart ecId={`${this && this.props && this.props.ecId || ''}_Chart@lvb909@${chart.type+index}`} width={canvasWidth} height={canvasHeight} data={chart.data} scale={chart.scale} padding="auto" forceFit>
                              <Legend ecId={`${this && this.props && this.props.ecId || ''}_Legend@6ge01n@${chart.type+index}`} />
                              <Axis ecId={`${this && this.props && this.props.ecId || ''}_Axis@iqbb3f@${chart.type+index}`} name="x" />
                              <Axis ecId={`${this && this.props && this.props.ecId || ''}_Axis@9l2z8c@${chart.type+index}`} name="y" />
                              <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@nvcl9p@${chart.type+index}`}
                                crosshairs={{
                                  type: "y"
                                }}
                              />
                              {/* <Geom type="areaStack" position="xd*yd" color={['category', ['l (90) 0:rgba(0, 146, 255, 1) 1:rgba(0, 146, 255, 0.1)', 'l (90) 0:rgba(0, 268, 0, 1) 1:rgba(0, 268, 0, 0.1)']]} />
                        <Geom type="areaStack" position="xd*yd" color={['category', ['rgba(0, 146, 255, 1)', '#00ff00']]} /> */}
                              <Geom ecId={`${this && this.props && this.props.ecId || ''}_Geom@n9ha46@${chart.type+index}`}
                                type="line"        
                                position="xd*yd"
                                size={2}
                                color={"category"}
                              // shape={"smooth"}   // 平滑曲线
                              />
                              <Geom ecId={`${this && this.props && this.props.ecId || ''}_Geom@jh486e@${chart.type+index}`}
                                type="point"
                                position="xd*yd"
                                size={4}
                                shape={"circle"}
                                color={"category"}
                                style={{
                                  stroke: "#fff",
                                  lineWidth: 1
                                }}
                              />
                            </Chart>
                            :
                            nodata
                        )
                      }

                      {
                        chart.type === "bubble" && (
                          !_.isEmpty(chart.data) ?
                            <div className="bubble-chart" style={{ width: canvasWidth, height: canvasHeight }} >
                              <div className="bubble-container">
                                <div className="bubble-item bubble-item-left" style={{ width: Math.sqrt(chart.data[0].percent) * 100, height: Math.sqrt(chart.data[0].percent) * 100, top: 70 + 10 * (1 - chart.data[0].percent), background: chart.data[0].color }}>
                                  <span className="bubble-label">
                                    {
                                      `${chart.data[0].percent * 100}%`
                                    }
                                  </span>
                                </div>
                              </div>
                              <div className="bubble-container">
                                <div className="bubble-item bubble-item-right" style={{ width: Math.sqrt(chart.data[1].percent) * 100, height: Math.sqrt(chart.data[1].percent) * 100, top: 70 + 10 * (1 - chart.data[1].percent), background: chart.data[1].color }}>
                                  <span className="bubble-label">
                                    {
                                      `${chart.data[1].percent * 100}%`
                                    }
                                  </span>
                                </div>
                              </div>
                            </div>
                            :
                            nodata
                        )
                      }

                      {
                        chart.rightLegend &&
                        <div style={{ width: rightLegendWidth, maxWidth: chart.maxWidth || 200, paddingRight: rightLegendRightPadding + "px" }}>
                          {
                            chart.data.map(d => {
                              return this.getLegendItem(rightLegendItemWidth, rightLegengItemHeight, `${(d.percent * 100).toFixed(2)}%`, d.item, d.color)
                            })
                          }
                        </div>
                      }
                    </div>

                    {
                      ["pie", "bubble", "line"].includes(chart.type) && !_.isEmpty(chart.data) &&
                      <div className="chart-item-bottom">
                        {
                          chart.slogan ?
                            <div className="slogan-wrapper" dangerouslySetInnerHTML={{ __html: this.getSloganHtml(chart.slogan) }}></div>
                            :
                            chart.data.map((d, i) => {
                              const rowMaxCount = 3
                              const width = (100 / Math.min(chart.data.length, rowMaxCount)) + "%"
                              let value
                              if (chart.type === "pie") {
                                value = `${d.percent * 100}%`
                              } else {
                                value = d.count + chart.unit
                              }
                              return this.getLegendItem(width, null, value, d.item, d.color, i % rowMaxCount != 0)
                            })
                        }
                      </div>
                    }
                  </Spin>
                </div>
              )
            })
          }
        </div>


        {
          moreDialogVisible && <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@s107rk`}
            className="wea-workrelate-portrait-more-dialog"
            hasScroll
            destroyBodyOnClose
            visible={moreDialogVisible}
            title={moreDialogTitle}
            icon="icon-coms02-Portrait-of-personnel" 
            iconBgcolor="#893D86"
            style={{
              width: 800,
              height: 465,
            }}
            buttons={
              [
                // <Button type="primary" onClick={this.onDialogSureClick}>
                //     {getLabel(826, '确定')}
                // </Button>,
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@7bqrbe@cancel`} type="ghost" onClick={this.onMoreDialogCancleClick}>
                  {getLabel(31129, '取消')}
                </Button>,
              ]
            }
            onCancel={this.onMoreDialogCancleClick}
            children={(
              // <WeaTable columns={moreDialogTableColumns} dataSource={moreDialogTableDataSource} pagination={false} scroll={{ y: 460 }} />  // 不分页
              <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@3r8g8r`}
                columns={moreDialogTableColumns}
                dataSource={moreDialogTableDataSource}
                scroll={{ y: 360 }}
                pagination={{
                  total: moreDialogTableTotal,
                  showTotal: () => getLabel(509103, '共{total}条').replace('{total}', moreDialogTableTotal),
                  current: moreDialogTablePageCurrent,
                  showQuickJumper: true,
                  pageSizeOptions: [10, 20, 50, 100],
                  pageSize: moreDialogTablePageSize,
                  showSizeChanger: true,
                  onChange: current => this.onDialogTablePageCurrentChange(current),
                  onShowSizeChange: (current, pageSize) => {
                    this.setState({
                      moreDialogTablePageCurrent: 1,
                      moreDialogTablePageSize: pageSize
                    }, () => {
                      this.getMoreDialogTableDatas()
                    })
                  }
                }}
                loading={moreDialogTableLoading}
              />
            )}
          />
        }
      </div>
    )
  }
}